﻿/*
 * @author: wizardc
 */

using System.IO;
using System.IO.Compression;
using Dou.Resource;
using Dou.Utils;
using DouEditor.Const;
using DouEditor.Utils;

namespace DouEditor.Resource.HotFixed
{
    /// <summary>
    /// 提取出增量包
    /// 将增量包打包为一个 zip 文件
    /// </summary>
    public class IncrementPack
    {
        private const string TempFolderName = "__TEMP";
        
        public void Build(BuildRule buildRule)
        {
            var tempPath = Path.Combine(buildRule.incrementOutputPath, TempFolderName);
            if (Directory.Exists(tempPath))
            {
                Directory.Delete(tempPath, true);
            }
            Directory.CreateDirectory(tempPath);

            var contrastHotFixFilePath = Path.Combine(buildRule.contrastPath, BuildConst.HotFixedManifestName);
            var contrastHotFix = new HotFixedManifest();
            contrastHotFix.Decode(File.ReadAllText(contrastHotFixFilePath));
            
            var copyHotFixFilePath = Path.Combine(buildRule.copyPath, BuildConst.HotFixedManifestName);
            var copyHotFix = new HotFixedManifest();
            copyHotFix.Decode(File.ReadAllText(copyHotFixFilePath));
            
            // 找出变动和新增的文件拷贝到 Temp 目录
            foreach (var kv in copyHotFix.fileInfoMap)
            {
                var fileInfo = kv.Value;
                if (!contrastHotFix.fileInfoMap.ContainsKey(fileInfo.fileName) || contrastHotFix.fileInfoMap[fileInfo.fileName].hashCode != fileInfo.hashCode)
                {
                    EditorUtil.CopyFile(Path.Combine(buildRule.copyPath, fileInfo.fileName), Path.Combine(tempPath, fileInfo.fileName));
                }
            }
            // HotFixed文件也需要一起拷贝到 Temp 目录
            EditorUtil.CopyFile(copyHotFixFilePath, Path.Combine(tempPath, BuildConst.HotFixedManifestName));

            // 打包为 Zip 包
            ZipFile.CreateFromDirectory(tempPath, Path.Combine(buildRule.incrementOutputPath, GetHotFixedZipName(buildRule)));
            
            Directory.Delete(tempPath, true);
        }

        private string GetHotFixedZipName(BuildRule buildRule)
        {
            return $"{buildRule.desc}_{buildRule.mainVersion}_{buildRule.subVersion}_{buildRule.hotFixedVersion}_{TimeUtil.FormatNowDate("yyyy_MM_dd_HH_mm_ss")}.zip";
        }
    }
}
